package com.xdtech.trans.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xdtech.common.utils.DateUtil;
import com.xdtech.common.utils.DateUtil.DateStyle;
import com.xdtech.sys.aspect.SystemControllerLog;
import com.xdtech.sys.controller.AuthLoginController;
import com.xdtech.sys.model.User;
import com.xdtech.sys.service.UserService;
import com.xdtech.sys.util.SessionContextUtil;
import com.xdtech.sys.vo.UserItem;
import com.xdtech.trans.model.Person;
import com.xdtech.trans.model.TransWebSite;
import com.xdtech.trans.service.PersonService;
import com.xdtech.trans.service.PriceConfigService;
import com.xdtech.trans.service.TransOrderScanService;
import com.xdtech.trans.service.TransOrderService;
import com.xdtech.trans.service.TransWebSiteService;
import com.xdtech.trans.util.TransConstants;
import com.xdtech.trans.vo.AppPerson;
import com.xdtech.trans.vo.PersonItem;
import com.xdtech.trans.vo.PriceConfigItem;
import com.xdtech.trans.vo.TransOrderItem;
import com.xdtech.trans.vo.TransOrderScanItem;
import com.xdtech.web.model.ComboBox;
import com.xdtech.web.model.Pagination;
import com.xdtech.web.model.ResultMessage;
import com.xdtech.web.util.AppReturnUtils;

/**
 * 
 * @author max.zheng
 * @create 2015-05-28 00:20:05
 * @since 1.0
 * @see
 */
@Controller
@Scope("prototype")
public class PersonController {
	private Log log = LogFactory.getLog(PersonController.class);
	@Autowired
	private PersonService personService;
	@Autowired
	private TransWebSiteService transWebSiteService;
	@Autowired
	private PriceConfigService priceConfigService;
	@Autowired
	private TransOrderService transOrderService;
	@Autowired
	private TransOrderScanService transOrderScanService;
	@Autowired
	private UserService userService;
	@RequestMapping(value="/person.do",params = "person")
	public ModelAndView skipPerson() {
		return new ModelAndView("trans/person/person_ftl");
	}
	
	@RequestMapping(value="/person.do",params="loadList")
	@ResponseBody
	public Map<String, Object> loadList(PersonItem item,Pagination pg) {
		UserItem userItem = SessionContextUtil.getCurrentUser();
		if (userItem!=null&&userItem instanceof PersonItem) {
			//物流员工
			PersonItem personItem = (PersonItem) userItem;
			String websiteIds = transWebSiteService.getPersonSubWebsiteIdsById(Long.valueOf(personItem.getWebsiteId()));
			item.setWebsiteIds(websiteIds);
		}else if (!userItem.isSuperuser()) {
			//系统用户，非超级用户
			item.setWebsiteIds("-1");
		}
		Map<String, Object> results =  personService.loadPageDataByConditions(pg,item,"findPersonByCondition");
		return results;
	}
	
	@RequestMapping(value="/person.do",params = "editPerson")
	@SystemControllerLog(description = "编辑")
	public ModelAndView editPerson(HttpServletRequest request,Long personId) {
		if (personId!=null) {
			request.setAttribute("isDisabled", "true");
			request.setAttribute("personItem", personService.loadPersonItem(personId));
		}else {
			//设置数据权限过滤
			UserItem currentUser = SessionContextUtil.getCurrentUser();
			if (currentUser.isSuperuser())
			{
				//超级管理员移除，数据过滤
				request.setAttribute("isDisabled", "false");
			}else {
				String currentSubWebsiteIds = "-1";
				if (currentUser instanceof PersonItem) {
					//物流员工
					PersonItem personItem = (PersonItem) currentUser;
					PersonItem creatPersonTemp = new PersonItem();
					creatPersonTemp.setWebsiteId(personItem.getWebsiteId());
					request.setAttribute("personItem", creatPersonTemp);
				}
				request.setAttribute("isDisabled", "true");
			}
		}
		return new ModelAndView("trans/person/editPerson_ftl");
	}
	
	@RequestMapping(value="/person.do",params = "savePerson")
	@ResponseBody
	@SystemControllerLog(description = "保存")
	public ResultMessage savePerson(PersonItem item) {
		ResultMessage r = new ResultMessage();
		//设置用户状态
		String status = "1".equals(item.getPositionStatus())?"1":"0";
		item.setStatus(status);
		if (personService.saveOrUpdatePerson(item)) {
			r.setSuccess(true);
		}else {
			r.setSuccess(false);
		}
		return r;
	}
	
	@RequestMapping(value="/person.do",params = "deletePersonItems")
	@ResponseBody
	@SystemControllerLog(description = "删除")
	public ResultMessage deletePersonItems(String ids) {
		ResultMessage r = new ResultMessage();
		if (StringUtils.isNotEmpty(ids)) {
			String[] tempIds = ids.split(",");
			List<Long> personIds = new ArrayList<Long>();
			for (String id : tempIds) {
				personIds.add(Long.valueOf(id));
			}
			personService.deletePersonInfo(personIds);
			r.setSuccess(true);
		}else {
			r.setSuccess(false);
		}
		return r;
	}

	@RequestMapping(value="/person.do",params = "loadPersonCombox")
	@ResponseBody
	public List<ComboBox> loadPersonCombox(String value,String text,String websiteId) {
		Long webId = 0L;
		List<Person> persons = personService.getPersonsByCurrentWebsite(webId);
		List<ComboBox> comboBoxs = new ArrayList<ComboBox>();
		for (Person p : persons)
		{
			comboBoxs.add(new ComboBox(p.getLoginName(), p.getName(), p.getLoginName().toString().equals(value)||p.getName().equals(text)));
		}
		return comboBoxs;
	}
	
	
	/********APP接口****************************************/
	/**
	 * 用户登录
	 * 
	 * @author max.zheng
	 * @create 2015-7-4下午11:49:03
	 * @modified by
	 * @param request
	 * @param response
	 * @param username
	 * @param password
	 */
	@RequestMapping(value = "/transPerson.action", params = "appLogin")
	@SystemControllerLog(description = "APP登录")
	public void appLogin(HttpServletRequest request,
			HttpServletResponse response, String username, String password) {
		ResultMessage r = new ResultMessage();
		PersonItem personItem = personService.loginCheck(username, password);
		if (personItem != null) {
			r.setMsg("登录成功");
			//shiro登录
			new AuthLoginController().login(username, password, "false", request);
			AppPerson appPerson = AppPerson.createPerson(personItem);
			r.setObj(appPerson);
			request.getSession().setAttribute("appPerson", appPerson);
		} else {
			r.setSuccess(false);
			r.setMsg("账号或密码有误");
		}
		AppReturnUtils.returnJsonpAsk(request, response, r);
	}
	
	/**
	 * 加载网点列表
	 * 
	 * @author max.zheng
	 * @create 2015-7-4下午11:49:19
	 * @modified by
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/transPerson.action", params = "loadWebsites")
	public void loadWebsites(HttpServletRequest request,HttpServletResponse response) {
		ResultMessage r = new ResultMessage();
		List<String> websiteNames = transWebSiteService.loadWebsiteNames();
		r.setObj(websiteNames);
		AppReturnUtils.returnJsonpAsk(request, response, r);
	}
	/**
	 * 加载价格设置
	 * 
	 * @author max.zheng
	 * @create 2015-7-4下午11:49:31
	 * @modified by
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/transPerson.action", params = "loadPriceConfig")
	public void loadPriceConfig(HttpServletRequest request,HttpServletResponse response) {
		ResultMessage r = new ResultMessage();
		PriceConfigItem priceConfigItem = priceConfigService.loadFirstPriceConfigItem();
		priceConfigItem.setQueryFields(null);
		r.setObj(priceConfigItem);
		AppReturnUtils.returnJsonpAsk(request, response, r);
	}
	
	@RequestMapping(value = "/transPerson.action", params = "saveTransOrder")
	@SystemControllerLog(description = "APP保存运单")
	public void saveTransOrder(HttpServletRequest request,HttpServletResponse response,TransOrderItem transOrderItem) {
		ResultMessage r = new ResultMessage();
		//数据校验
		if(StringUtils.isBlank(transOrderItem.getStartWebsite())) {
			r.setSuccess(false);
			r.setMsg("起始站为空");
		}else if (StringUtils.isBlank(transOrderItem.getEndWebsite())) {
			r.setSuccess(false);
			r.setMsg("目的站为空");
		}else if (StringUtils.isBlank(transOrderItem.getPayWebsite())) {
			r.setSuccess(false);
			r.setMsg("收款网点为空");
		}else if (transOrderItem.getWeight()==null&&transOrderItem.getTotal()==null) {
			r.setSuccess(false);
			r.setMsg("运单重量或费用不能为空");
		}else {
			if (StringUtils.isBlank(transOrderItem.getSalesman())) {
				AppPerson appPerson = (AppPerson) request.getSession().getAttribute("appPerson");
				if (appPerson!=null) {
					transOrderItem.setSalesman(appPerson.getLoginName());
					transOrderItem.setCreator(appPerson.getLoginName());
				}
			}else {
				User user = userService.getUserByName(transOrderItem.getSalesman());
				if (user!=null) {
					transOrderItem.setCreator(user.getLoginName());
					transOrderItem.setSalesman(user.getName());
				}
			}
			String rs = transOrderService.saveTransOrderWithApp(transOrderItem);
			if (StringUtils.isNotBlank(rs)) {
				if ("运单号已存在".equals(rs)) {
					r.setSuccess(false);
					r.setMsg(rs);
				}else {
					r.setSuccess(false);
					r.setMsg("运单保存成功；但是，"+rs);
				}
				
			}
		}
		
		AppReturnUtils.returnJsonpAsk(request, response, r);
	}
	
	@RequestMapping(value = "/transPerson.action", params = "loadTransOrders")
	@SystemControllerLog(description = "APP加载运单")
	public void loadTransOrders(HttpServletRequest request,HttpServletResponse response,PersonItem item,Pagination pg) {
		ResultMessage r = new ResultMessage();
		List<TransOrderItem> transOrderItems = new ArrayList<TransOrderItem>();
		transOrderItems.add(new TransOrderItem());
		r.setObj(transOrderItems);
		AppReturnUtils.returnJsonpAsk(request, response, r);
	}
	
	@RequestMapping(value = "/transPerson.action", params = "deliverScan")
	@SystemControllerLog(description = "APP派件")
	public void deliverScan(HttpServletRequest request,HttpServletResponse response,TransOrderScanItem transOrderScanItem) {
		ResultMessage r = new ResultMessage();
		AppPerson appPerson = (AppPerson) request.getSession().getAttribute("appPerson");
		if (appPerson!=null) {
			transOrderScanItem.setScanOperator(appPerson.getName());
			transOrderScanItem.setCreator(appPerson.getLoginName());
		}else if(StringUtils.isNotBlank(transOrderScanItem.getScanOperator())) {
			User user = userService.getUserByName(transOrderScanItem.getScanOperator());
			if (user!=null) {
				transOrderScanItem.setScanOperator(user.getName());
				transOrderScanItem.setCreator(user.getLoginName());
			}
		}
		transOrderScanItem.setScanFrom(TransConstants.FROM_APP);
		transOrderScanItem.setScanTime(DateUtil.getDate(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
		String rs = transOrderScanService.deliverScanWithApp(transOrderScanItem);
		if (StringUtils.isNotBlank(rs)) {
			r.setSuccess(false);
			r.setMsg(rs);
		}
		AppReturnUtils.returnJsonpAsk(request, response, r);
	}
	
	@RequestMapping(value = "/transPerson.action", params = "loadOrder")
	@SystemControllerLog(description = "APP加载运单")
	public void loadOrder(HttpServletRequest request,HttpServletResponse response,String orderNo) {
		ResultMessage r = new ResultMessage();
		TransOrderItem transOrderItem = transOrderService.loadTransOrderItemByOrderNo(orderNo);
		if (transOrderItem==null) {
			r.setSuccess(false);
			r.setMsg("无该单号记录");
		}else {
			r.setObj(transOrderItem);
		}
		AppReturnUtils.returnJsonpAsk(request, response, r);
	}
	
	@RequestMapping(value = "/transPerson.action", params = "logout")
	@SystemControllerLog(description = "APP退出")
	public void logout(HttpServletRequest request,
			HttpServletResponse response,String username) {
		request.getSession().removeAttribute("appPerson");
		AppReturnUtils.returnJsonpAsk(request, response, new ResultMessage(
				true, "退出成功"));
	}
}
